import { window, workspace } from 'vscode'
import { EnginesEnum, secretMap } from '../types'

const BaiduTranslate = require('node-baidu-translate')

const tencentcloud = require('tencentcloud-sdk-nodejs')
const TmtClient = tencentcloud.tmt.v20180321.Client

const CryptoJS = require('crypto-js')
const axios = require('axios')

// 获取配置的密钥
function getSecret(type: EnginesEnum) {
  const [appid, secret] = workspace.getConfiguration('zflTranslation')[secretMap[type]].split(',')
  if (!(appid && secret)) {
    window.showInformationMessage(`${type}翻译未配置,请现在设置中配置`)
  }
  return [appid, secret]
}
// 确保只有一个实例
function createSingletonInstance<T>(constructor: any, ...args: any[]): T {
  if (!constructor.instance) {
    constructor.instance = new constructor(...args)
  }
  return constructor.instance
}

// 百度翻译
async function baidu(text: string, language: string) {
  const [appid, secretKey] = getSecret(EnginesEnum.baidu)
  const baiduInstance = createSingletonInstance(BaiduTranslate, appid, secretKey) as any
  const res = await baiduInstance.translate(text, language)
  return res.trans_result[0].dst
}

// 腾讯翻译
async function tencent(text: string, language: string) {
  const [SecretId, SecretKey] = getSecret(EnginesEnum.tencent)
  const clientConfig = {
    credential: {
      secretId: SecretId,
      secretKey: SecretKey,
    },
    region: 'ap-chongqing',
    profile: {
      httpProfile: {
        endpoint: 'tmt.tencentcloudapi.com',
      },
    },
  }
  const tencentInstance = createSingletonInstance(TmtClient, clientConfig) as any
  const params = {
    SourceText: text,
    Source: 'auto',
    Target: language,
    ProjectId: 0,
  }
  const res = await tencentInstance.TextTranslate(params)
  return res.TargetText
}

// 有道翻译
async function youdao(text: string, language: string) {
  const [appKey, key] = getSecret(EnginesEnum.youdao)
  const salt = new Date().getTime()
  const curtime = Math.round(new Date().getTime() / 1000)
  const str1 = appKey + truncate(text) + salt + curtime + key
  const sign = CryptoJS.SHA256(str1).toString(CryptoJS.enc.Hex)
  const data = {
    q: text,
    appKey: appKey,
    salt: salt,
    from: 'auto',
    to: language,
    sign: sign,
    signType: 'v3',
    curtime: curtime,
  }
  const res = await axios.get('https://openapi.youdao.com/api', {
    params: data,
  })
  return res.data.translation[0]
}

function truncate(q: string) {
  const len = q.length
  if (len <= 20) return q
  return q.substring(0, 10) + len + q.substring(len - 10, len)
}


const engines = {
  baidu,
  tencent,
  youdao,
}
export default engines
